package ace.module.oauth2.server.core.impl.converter.impl;

import ace.module.oauth2.server.core.impl.converter.Oauth2ObjectJsonConverter;
import ace.module.oauth2.server.core.impl.converter.TokenSettingsFromJsonConverter;
import java.util.Map;
import lombok.AllArgsConstructor;
import org.springframework.security.oauth2.server.authorization.settings.ConfigurationSettingNames;
import org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.stereotype.Component;

/**
 * @author caspar
 * @date 2023/10/12 11:50
 */
@AllArgsConstructor
@Component
public class TokenSettingsFromJsonConverterImpl implements TokenSettingsFromJsonConverter {
  private final Oauth2ObjectJsonConverter oAuth2ObjectJsonConverter;

  @Override
  public TokenSettings convert(String source) {
    Map<String, Object> tokenSettingsMap = this.oAuth2ObjectJsonConverter.toMap(source);
    TokenSettings.Builder tokenSettingsBuilder = TokenSettings.withSettings(tokenSettingsMap);
    if (!tokenSettingsMap.containsKey(ConfigurationSettingNames.Token.ACCESS_TOKEN_FORMAT)) {
      tokenSettingsBuilder.accessTokenFormat(OAuth2TokenFormat.SELF_CONTAINED);
    }
    return tokenSettingsBuilder.build();
  }
}
